/*
 * Author Hung Tran
 */
package viettravel.guiandevent.place;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.holoeverywhere.app.AlertDialog;
import org.json.JSONArray;
import org.json.JSONObject;
import viettravel.DAO.ActivityDAO;
import viettravel.DAO.ProvinceDAO;
import viettravel.DAO.RegionDAO;
import viettravel.DAO.SpecialtyDAO;
import viettravel.DAO.TouristFormDAO;
import viettravel.DTO.DBCommunication;
import viettravel.DTO.JSONParser;
import viettravel.DTO.ViettravelDTO;
import viettravel.common.Constants;
import viettravel.guiandevent.R;
import viettravel.guiandevent.customeview.WidgetContainer;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.internal.widget.IcsAdapterView;
import com.actionbarsherlock.internal.widget.IcsAdapterView.OnItemSelectedListener;
import com.actionbarsherlock.internal.widget.IcsSpinner;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;

public class NewPlaceActivity extends SherlockActivity {

	public static String URL = "http://maps.googleapis.com/maps/api/geocode/json?address=";
	public static String SENSOR = "&sensor=true";

	private Context mContext;
	private NewPlaceExpandableAdapter mExpandableAdapter;
	private ExpandableListView mExpanableListView;
	private ArrayList<NewPlaceExpadableHeaderObject> mHeaderList;
	private ViettravelDTO mViettravelDTO;
	private ArrayList<NewPlaceExpadableChildObject> childListActivity;
	private ArrayList<NewPlaceExpadableChildObject> childListTourist;
	private ArrayList<NewPlaceExpadableChildObject> childListSpecialty;
	private RegionDAO mCurrentRegion;
	//private PlaceDAO newPlace;

	// view
	private ImageView newPlaceRightArrow;
	private ImageView newPlaceLeftArrow;
	private Gallery mGallery;
	private TextView placeName;
	private TextView placeDescription;
	private int mSelectedImagePosition = 0;
	private int mWidth = Constants.SLIDE_IMAGE_WIDTH;
	private int mHeight = Constants.SLIDE_IMAGE_HEIGHT;
	private List<Drawable> mListImage;
	private GalleryImageAdapter galImageAdapter;
	private static final int RESULT_LOAD_IMAGE = 1;
	private static final int RESULT_LOAD_PLACE = 2;

	// data for post
	private String mPlaceName;
	private String mPlaceDescription;
	@SuppressWarnings("unused")
	private int mRegionId;
	private int mProvinceId;
	private Double mLatitutde;
	private Double mLongtitude;
	private ArrayList<Integer> mListActivity;
	private ArrayList<Integer> mListTouristForm;
	private ArrayList<Integer> mListSpecialty;
	private ArrayList<byte[]> mListArrayByte;
	private ArrayList<String> mListImageString;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setTheme(Constants.THEME);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_new_place);
		mContext = this;
		mViettravelDTO = ViettravelDTO.getInstance();
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayHomeAsUpEnabled(false);
		actionBar.setHomeButtonEnabled(true);
		actionBar.setIcon(R.drawable.ic_back_arrow);
		actionBar.setTitle(R.string.newplace_title);
		actionBar.setBackgroundDrawable(Constants.APP_DRAWABLE);
		initParameter();

		placeName = (TextView) findViewById(R.id.newPlaceName);
		placeName.setTypeface(Constants.TYPEFACE_NYALA);
		placeDescription = (TextView) findViewById(R.id.newPlaceDescription);
		placeDescription.setTypeface(Constants.TYPEFACE_NYALA);
		
		renderHeader();

		newPlaceLeftArrow = (ImageView) findViewById(R.id.newPlaceLeftArrow);
		newPlaceRightArrow = (ImageView) findViewById(R.id.newPlaceRightArrow);
		mGallery = (Gallery) findViewById(R.id.newPlaceGallery);
		mHeaderList = new ArrayList<NewPlaceExpadableHeaderObject>();
		mExpanableListView = (ExpandableListView) findViewById(R.id.newPlaceOptionList);
		updateExpandableList(mExpanableListView);
		renderRegionSpinnerList();
		mListImage = new ArrayList<Drawable>();
		galImageAdapter = new GalleryImageAdapter(mContext, mListImage, mWidth,
				mHeight);
		renderGallery();
		expandAll();
		Button newPlaceCheckPlaceName = (Button) findViewById(R.id.newPlaceButtonCheckPlaceName);
		newPlaceCheckPlaceName.setOnClickListener(checkNameOnClickListener);
	}

	private void initParameter() {
		mPlaceName = "";
		mPlaceDescription = "";
		mRegionId = 0;
		mProvinceId = 0;
		mListActivity = new ArrayList<Integer>();
		mListTouristForm = new ArrayList<Integer>();
		mListSpecialty = new ArrayList<Integer>();
		mListArrayByte = new ArrayList<byte[]>();
		mListImageString = new ArrayList<String>();
	}

	OnClickListener checkNameOnClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			setData();
			if (mPlaceName != "") {
				String name = Constants.convertUTF8String(mPlaceName);
				name = name.replaceAll(" ", "%20");
				StringBuilder buildr = new StringBuilder();
				buildr.append(URL);
				buildr.append(name);
				buildr.append(SENSOR);
				new CheckPlace().execute(buildr.toString());
			}
		}
	};

	private void renderHeader() {
		WidgetContainer newPlaceRegionProvinceHeader = (WidgetContainer) findViewById(R.id.newPlaceRegionProvinceHeader);
		newPlaceRegionProvinceHeader.setTitle(
				getString(R.string.newplace_header_region_province),
				Gravity.CENTER_HORIZONTAL);

		WidgetContainer newPlaceImageHeader = (WidgetContainer) findViewById(R.id.newPlaceImageHeader);
		newPlaceImageHeader.setTitle(getString(R.string.newplace_header_image),
				Gravity.CENTER_HORIZONTAL);

		WidgetContainer newPlaceInformationHeader = (WidgetContainer) findViewById(R.id.newPlaceInformationHeader);
		newPlaceInformationHeader.setTitle(
				getString(R.string.newplace_header_information),
				Gravity.CENTER_HORIZONTAL);
	}

	private void renderGallery() {
		newPlaceLeftArrow.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mSelectedImagePosition > 0) {
					--mSelectedImagePosition;
				}
				mGallery.setSelection(mSelectedImagePosition, false);
			}
		});

		newPlaceRightArrow.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (mSelectedImagePosition < mListImage.size() - 1) {
					++mSelectedImagePosition;
				}
				mGallery.setSelection(mSelectedImagePosition, false);
			}
		});

		mGallery.setOnItemSelectedListener(new android.widget.AdapterView.OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int pos, long id) {
				mSelectedImagePosition = pos;
				if (mSelectedImagePosition > 0
						&& mSelectedImagePosition < mListImage.size() - 1) {
					newPlaceLeftArrow.setImageDrawable(getResources()
							.getDrawable(R.drawable.ic_left_arrow));
					newPlaceRightArrow.setImageDrawable(getResources()
							.getDrawable(R.drawable.ic_right_arrow));
				} else if (mSelectedImagePosition == 0) {
					newPlaceLeftArrow.setImageDrawable(getResources()
							.getDrawable(R.drawable.ic_left_arrow));
				} else if (mSelectedImagePosition == mListImage.size() - 1) {
					newPlaceRightArrow.setImageDrawable(getResources()
							.getDrawable(R.drawable.ic_right_arrow));
				}
				changeBorderForSelectedImage(mSelectedImagePosition);
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

		mGallery.setOnItemLongClickListener(new android.widget.AdapterView.OnItemLongClickListener() {
			@SuppressWarnings("deprecation")
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View v,
					int position, long id) {
				final int pos = position;
				AlertDialog alertDialog = new AlertDialog.Builder(mContext)
						.create();
				alertDialog.setTitle(getString(R.string.newplace_popup_title));
				alertDialog
						.setMessage(getString(R.string.newplace_popup_message));
				alertDialog.setButton(getString(R.string.newplace_popup_ok),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int which) {
								mListImage.remove(pos);
								renderImageAdapter();
							}
						});
				alertDialog.setIcon(R.drawable.abs__ic_clear_normal);
				alertDialog.show();
				return true;
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.v(Constants.TAG, requestCode+"");
		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
				&& null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			if (cursor.moveToFirst()) {
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);
				cursor.close();
				Drawable d = Drawable.createFromPath(picturePath);
				d = Constants.reduceImage(d, Constants.SLIDE_IMAGE_WIDTH,
						Constants.SLIDE_IMAGE_HEIGHT);
				mListImage.add(d);
				renderImageAdapter();
			}
		}
		if (requestCode == RESULT_LOAD_PLACE && resultCode == RESULT_OK
				&& null != data) {
			Log.v(Constants.TAG, "adawdawd");
			mPlaceName = data.getStringExtra(Constants.EXTRA_PLACE_NAME);
			placeName.setText(mPlaceName);
			mLatitutde = data.getDoubleExtra(Constants.EXTRA_PLACE_LAT, 0);
			mLongtitude = data.getDoubleExtra(Constants.EXTRA_PLACE_LONG, 0);
			
			Log.v(Constants.TAG + "main",mPlaceName);
			Log.v(Constants.TAG + "main",mLatitutde+"");
			Log.v(Constants.TAG + "main",mLongtitude+"");
		}
	}

	private void renderImageAdapter() {
		Log.v(Constants.TAG, "Error here");
		galImageAdapter.setListImage(mListImage);
		mGallery.setAdapter(galImageAdapter);
		if (mListImage.size() == 1)
			newPlaceRightArrow.setImageDrawable(getResources().getDrawable(
					R.drawable.arrow_right_disabled));
		Log.v(Constants.TAG, "Error not here");
	}

	private void changeBorderForSelectedImage(int selectedItemPos) {

		int count = mGallery.getChildCount();

		for (int i = 0; i < count; i++) {
			ImageView imageView = (ImageView) mGallery.getChildAt(i);
			imageView.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.customview_sliding_image_border));
			imageView.setPadding(3, 3, 3, 3);
		}
		ImageView imageView = (ImageView) mGallery.getSelectedView();
		imageView.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.customview_image_selected_border));
		imageView.setPadding(3, 3, 3, 3);
	}

	// Render province list
	private void renderProvinceSpinnerList() {
		ArrayList<ProvinceDAO> listProvince = mViettravelDTO
				.findProvinceByRegionId(mCurrentRegion.getRegionId());
		final SpinnerProvinceAdapter spinnerProvinceAdapter = new SpinnerProvinceAdapter(
				mContext, listProvince);
		IcsSpinner regionSpinner = (IcsSpinner) findViewById(R.id.spinnerListProvince);
		regionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(IcsAdapterView<?> parent, View view,
					int position, long id) {
				ProvinceDAO p = (ProvinceDAO) spinnerProvinceAdapter
						.getItem(position);
				mProvinceId = p.getProvinceId();
			}

			@Override
			public void onNothingSelected(IcsAdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
		regionSpinner.setAdapter(spinnerProvinceAdapter);
	}

	// Render region list
	private void renderRegionSpinnerList() {
		ArrayList<RegionDAO> listRegion = mViettravelDTO.findAllRegion();
		final SpinnerRegionAdapter spinnerRegionAdapter = new SpinnerRegionAdapter(
				mContext, listRegion);
		IcsSpinner regionSpinner = (IcsSpinner) findViewById(R.id.spinnerListRegion);
		regionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(IcsAdapterView<?> parent, View view,
					int position, long id) {
				mCurrentRegion = (RegionDAO) spinnerRegionAdapter
						.getItem(position);
				mRegionId = mCurrentRegion.getRegionId();
				renderProvinceSpinnerList();
			}

			@Override
			public void onNothingSelected(IcsAdapterView<?> parent) {
				// TODO Auto-generated method stub

			}
		});
		regionSpinner.setAdapter(spinnerRegionAdapter);
	}

	// Expandable list
	public void updateExpandableList(ExpandableListView e) {
		childListActivity = new ArrayList<NewPlaceExpadableChildObject>();
		ArrayList<ActivityDAO> listActivity = mViettravelDTO
				.findAllActivities();
		for (ActivityDAO a : listActivity) {
			NewPlaceExpadableChildObject c = new NewPlaceExpadableChildObject(
					false, a);
			childListActivity.add(c);
		}
		mHeaderList.add(new NewPlaceExpadableHeaderObject(childListActivity,
				getString(R.string.newplace_header_activity)));

		childListTourist = new ArrayList<NewPlaceExpadableChildObject>();
		ArrayList<TouristFormDAO> listTourist = mViettravelDTO
				.findAllTourists();
		for (TouristFormDAO a : listTourist) {
			NewPlaceExpadableChildObject c = new NewPlaceExpadableChildObject(
					false, a);
			childListTourist.add(c);
		}
		mHeaderList.add(new NewPlaceExpadableHeaderObject(childListTourist,
				getString(R.string.newplace_header_tourist)));

		childListSpecialty = new ArrayList<NewPlaceExpadableChildObject>();
		ArrayList<SpecialtyDAO> listSpecialty = mViettravelDTO
				.findAllSpecialties();
		for (SpecialtyDAO a : listSpecialty) {
			NewPlaceExpadableChildObject c = new NewPlaceExpadableChildObject(
					false, a);
			childListSpecialty.add(c);
		}
		mHeaderList.add(new NewPlaceExpadableHeaderObject(childListSpecialty,
				getString(R.string.newplace_header_specialty)));

		mExpandableAdapter = new NewPlaceExpandableAdapter(this, mHeaderList);
		e.setAdapter(mExpandableAdapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu _menu) {
		SubMenu subMenuSort = _menu.addSubMenu(this
				.getString(R.string.newplace_submenu_header));
		subMenuSort.add(Menu.NONE, R.id.newplace_submenuitem_addimage,
				Menu.NONE, this.getString(R.string.newplace_submenu_add_image))
				.setIcon(R.drawable.ic_add);
		subMenuSort.add(Menu.NONE, R.id.newplace_submenuitem_commit, Menu.NONE,
				this.getString(R.string.newplace_submenu_commit)).setIcon(
				R.drawable.abs__btn_cab_done_holo_light);

		MenuItem menuItemSort = subMenuSort.getItem();
		menuItemSort.setIcon(R.drawable.ic_list_w);
		menuItemSort.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS
				| MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		return super.onCreateOptionsMenu(_menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home: {
			finish();
			return true;
		}
		case R.id.newplace_submenuitem_addimage: {
			Intent i = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(i, RESULT_LOAD_IMAGE);
			return true;
		}
		case R.id.newplace_submenuitem_commit: {
			setData();
			new PostData().execute("...");
			return true;
		}
		default:
			return super.onMenuItemSelected(featureId, item);
		}
	}

	private void expandAll() {
		int count = mExpandableAdapter.getGroupCount();
		for (int i = 0; i < count; i++) {
			mExpanableListView.expandGroup(i);
		}
	}

	// Get data
	private void setData() {
		
		mPlaceName = placeName.getText().toString().replace("\"", "&#34;");
		mPlaceDescription = placeDescription.getText().toString().replace("\"", "&#34;");
		mListActivity.clear();
		mListTouristForm.clear();
		mListSpecialty.clear();
		mListArrayByte.clear();
		for (NewPlaceExpadableChildObject a : childListActivity) {
			if (a.getIsChecked())
				mListActivity.add(a.getCommonDao().getID());
		}
		for (NewPlaceExpadableChildObject a : childListTourist) {
			if (a.getIsChecked())
				mListTouristForm.add(a.getCommonDao().getID());
		}
		for (NewPlaceExpadableChildObject a : childListSpecialty) {
			if (a.getIsChecked())
				mListSpecialty.add(a.getCommonDao().getID());
		}
		for (int i = 0; i < mListImage.size(); i++) {
			mListArrayByte.add(Constants.drawable2ByteArray(mListImage.get(i)));
		}

		for (int i = 0; i < mListArrayByte.size(); i++) {
			mListImageString.add(Constants.byteArray2String(mListArrayByte
					.get(i)));
		}
		/*
		 * Drawable d = Constants.ByteArray2Image(mListArrayByte.get(0));
		 * mListImage.add(d); renderImageAdapter();
		 */

	}

	private Boolean postNewPlace() {
		JSONObject json = new JSONParser().makeJsonPlace(mPlaceName,
				mPlaceDescription, mLatitutde, mLongtitude, mProvinceId,
				mListActivity, mListSpecialty, mListTouristForm,
				mListImageString);
		Log.d("NEW PLACE", json.toString());
		return DBCommunication.postData(Constants.ROOT,
				Constants.SUFFIX_POST_PLACES, json);
	}

	public class PostData extends AsyncTask<String, Void, Boolean> {

		@Override
		protected Boolean doInBackground(String... params) {
			return postNewPlace();
		}

		private ProgressDialog mProgressDialog;

		@Override
		protected void onPreExecute() {
			mProgressDialog = new ProgressDialog(NewPlaceActivity.this);
			mProgressDialog.setMessage("Post data...");
			mProgressDialog.setCancelable(false);
			mProgressDialog.setIndeterminate(true);
			mProgressDialog.show();
		};

		@Override
		protected void onPostExecute(Boolean result) {
			if (mProgressDialog.isShowing()) {
				mProgressDialog.dismiss();
				finish();
			}
		}
	}

	public class CheckPlace extends AsyncTask<String, Integer, String> {
		private ProgressDialog mProgressDialog;

		@Override
		protected void onPreExecute() {
			mProgressDialog = new ProgressDialog(NewPlaceActivity.this);
			mProgressDialog.setMessage("Checking place...");
			mProgressDialog.setCancelable(false);
			mProgressDialog.setIndeterminate(true);
			mProgressDialog.show();
		};

		@Override
		protected String doInBackground(String... params) {
			java.net.URL url = null;
			try {
				url = new java.net.URL(params[0]);
			} catch (MalformedURLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

			try {
				String jsonString = JSONParser.getResponseFromUrl(url);
				return jsonString;

			} catch (Exception e) {
				return null;
			}
		}

		protected void onPostExecute(String result) {
			if (mProgressDialog.isShowing()) {
				mProgressDialog.dismiss();
				if (!result.equals(null)) {
					JSONObject jsonObject;
					try {
						jsonObject = new JSONObject(result);
						Log.d("New", jsonObject.getString(Constants.TAG_STATUS));
						Intent i = new Intent(NewPlaceActivity.this,
								ListCheckPlaceName.class);
						if (jsonObject.getString(Constants.TAG_STATUS).equals(
								"ZERO_RESULTS")) {
							i.putExtra(
									Constants.EXTRA_NEWPLACE_CHECKNAME_VALUE, 0);
						}
						if (jsonObject.getString(Constants.TAG_STATUS).equals(
								"OK")) {
							JSONArray array = jsonObject
									.getJSONArray(Constants.TAG_RESULTS);
							ArrayList<String> listLocation = new ArrayList<String>();
							for (int k = 0; k < array.length(); k++) {
								listLocation.add(array.getString(k));
							}

							i.putExtra(
									Constants.EXTRA_NEWPLACE_CHECKNAME_VALUE, 1);
							i.putExtra(Constants.LOCATIONLIST, listLocation);
						}
						i.putExtra(
								Constants.EXTRA_NEWPLACE_CHECKNAME_PLACENAME,
								placeName.getText().toString());
						startActivityForResult(i, RESULT_LOAD_PLACE);

					} catch (Exception e) {
						// TODO: handle exception
					}

				}
			}
		}
	}
}
